<template>
  <div class="profile-container">
    <!-- 用户基本信息卡片 -->
    <el-card class="user-info-card">
      <div class="user-header">
        <div class="avatar-section">
          <el-avatar 
            :size="80" 
            :src="ImageUtils.getImageUrl(currentUser?.userAvatar)"
            class="user-avatar"
          >
            {{ currentUser?.userName?.charAt(0) || 'U' }}
          </el-avatar>
        </div>
        <div class="user-details">
          <h2 class="user-name">{{ currentUser?.userName || '未设置昵称' }}</h2>
          <p class="user-account">@{{ currentUser?.userAccount }}</p>
          <el-tag 
            :type="currentUser?.userRole === 'admin' ? 'danger' : 'primary'"
            effect="light"
            size="small"
            round
          >
            {{ getRoleText(currentUser?.userRole) }}
          </el-tag>
          <p class="user-profile">{{ currentUser?.userProfile || '这个人很懒，什么都没留下' }}</p>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="editProfile">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
          <el-button @click="changePassword">
            <el-icon><Lock /></el-icon>
            修改密码
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><DocumentChecked /></el-icon>
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.totalProblems }}</h3>
            <p class="stat-label">已完成题目</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon easy">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.easyProblems }}</h3>
            <p class="stat-label">简单题目</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon medium">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.mediumProblems }}</h3>
            <p class="stat-label">中等题目</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon hard">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="stat-info">
            <h3 class="stat-number">{{ stats.hardProblems }}</h3>
            <p class="stat-label">困难题目</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最近活动 -->
    <el-card class="activity-card">
      <template #header>
        <div class="card-header">
          <h3>最近活动</h3>
          <el-button text @click="viewAllActivity">查看全部</el-button>
        </div>
      </template>
      <div class="activity-list">
        <div v-for="activity in recentActivities" :key="activity.id" class="activity-item">
          <div class="activity-icon">
            <el-icon :class="getActivityIconClass(activity.type)">
              <component :is="getActivityIcon(activity.type)" />
            </el-icon>
          </div>
          <div class="activity-content">
            <p class="activity-title">{{ activity.title }}</p>
            <p class="activity-time">{{ formatDate(activity.time) }}</p>
          </div>
        </div>
        <el-empty v-if="recentActivities.length === 0" description="暂无活动记录" />
      </div>
    </el-card>

    <!-- 快速操作 -->
    <el-card class="quick-actions-card">
      <template #header>
        <h3>快速操作</h3>
      </template>
      <div class="quick-actions">
        <el-button 
          class="action-btn" 
          @click="goToProblemList"
          :icon="List"
        >
          <span>题目列表</span>
        </el-button>
        <el-button 
          class="action-btn" 
          @click="goToHistory"
          :icon="Clock"
        >
          <span>做题历史</span>
        </el-button>
        <el-button 
          class="action-btn" 
          @click="goToFavorites"
          :icon="Star"
        >
          <span>我的收藏</span>
        </el-button>
        <el-button 
          class="action-btn" 
          @click="editProfile"
          :icon="Setting"
        >
          <span>账户设置</span>
        </el-button>
      </div>
    </el-card>

    <!-- 账户信息 -->
    <el-card class="account-info-card">
      <template #header>
        <h3>账户信息</h3>
      </template>
      <div class="info-grid">
        <div class="info-item">
          <span class="label">注册时间</span>
          <span class="value">{{ formatDate(currentUser?.createTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">最后更新</span>
          <span class="value">{{ formatDate(currentUser?.updateTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">用户ID</span>
          <span class="value">{{ currentUser?.id || '未知' }}</span>
        </div>
      </div>
    </el-card>

    <!-- 调试信息 -->
    <el-card class="debug-card" v-if="showDebug">
      <template #header>
        <h4>调试信息</h4>
      </template>
      <pre>{{ JSON.stringify(currentUser, null, 2) }}</pre>
    </el-card>

    <div class="debug-toggle">
      <el-button @click="showDebug = !showDebug" text>
        {{ showDebug ? '隐藏' : '显示' }}调试信息
      </el-button>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      :before-close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePasswordDialogClose">取消</el-button>
          <el-button type="primary" :loading="passwordLoading" @click="handlePasswordSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { UserControllerService } from '../services/UserControllerService'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { 
  Edit, 
  Lock, 
  DocumentChecked, 
  CircleCheck, 
  Warning, 
  CircleClose,
  List,
  Clock,
  Star,
  Setting,
  TrophyBase,
  Calendar,
  User
} from '@element-plus/icons-vue'
import { ImageUtils } from '../utils/imageUtils'
import type { UserUpdatePasswordRequest } from '../models/UserUpdatePasswordRequest'

const router = useRouter()
const userStore = useUserStore()
const showDebug = ref(false)

// 计算属性
const currentUser = computed(() => userStore.currentUser)

// 统计数据 (模拟数据，实际应从API获取)
const stats = reactive({
  totalProblems: 156,
  easyProblems: 89,
  mediumProblems: 52,
  hardProblems: 15
})

// 最近活动数据 (模拟数据)
const recentActivities = ref([
  {
    id: 1,
    type: 'solve',
    title: '完成了题目：两数之和',
    time: new Date().toISOString()
  },
  {
    id: 2,
    type: 'favorite',
    title: '收藏了题目：最长公共子序列',
    time: new Date(Date.now() - 3600000).toISOString()
  },
  {
    id: 3,
    type: 'achievement',
    title: '获得成就：初出茅庐',
    time: new Date(Date.now() - 7200000).toISOString()
  }
])

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordLoading = ref(false)

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为 8 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const getRoleText = (role?: string) => {
  switch (role) {
    case 'admin':
      return '管理员'
    case 'user':
      return '普通用户'
    default:
      return '未知角色'
  }
}

const formatDate = (dateString?: string) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

const editProfile = () => {
  router.push('/profile/edit')
}

// 修改密码
const changePassword = () => {
  passwordDialogVisible.value = true
}

const handlePasswordDialogClose = () => {
  passwordDialogVisible.value = false
  resetPasswordForm()
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return

  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return

    await ElMessageBox.confirm(
      '确定要修改密码吗？修改后需要重新登录。',
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    passwordLoading.value = true

    const updateRequest: UserUpdatePasswordRequest = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }

    const response = await UserControllerService.updatePassword(updateRequest)
    
    if (response.code === 0) {
      ElMessage.success('密码修改成功，请重新登录')
      passwordDialogVisible.value = false
      resetPasswordForm()
      // 清除登录状态，跳转到登录页
      await userStore.logout()
      router.push('/login')
    } else {
      throw new Error(response.message || '密码修改失败')
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败: ' + (error.message || '未知错误'))
  } finally {
    passwordLoading.value = false
  }
}

// 活动相关
const getActivityIcon = (type: string) => {
  switch (type) {
    case 'solve':
      return DocumentChecked
    case 'favorite':
      return Star
    case 'achievement':
      return TrophyBase
    default:
      return Calendar
  }
}

const getActivityIconClass = (type: string) => {
  switch (type) {
    case 'solve':
      return 'activity-solve'
    case 'favorite':
      return 'activity-favorite'
    case 'achievement':
      return 'activity-achievement'
    default:
      return 'activity-default'
  }
}

// 快速操作
const goToProblemList = () => {
  ElMessage.info('题目列表功能开发中...')
}

const goToHistory = () => {
  ElMessage.info('做题历史功能开发中...')
}

const goToFavorites = () => {
  ElMessage.info('我的收藏功能开发中...')
}

const viewAllActivity = () => {
  ElMessage.info('查看全部活动功能开发中...')
}

// 生命周期
onMounted(async () => {
  // 获取当前用户信息
  if (!currentUser.value) {
    await userStore.getCurrentUser()
  }
  
  // TODO: 获取用户统计数据
  // await loadUserStats()
  
  // TODO: 获取最近活动
  // await loadRecentActivities()
})
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 用户信息卡片 */
.user-info-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.user-header {
  display: flex;
  align-items: center;
  padding: 30px;
  gap: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.avatar-section {
  flex-shrink: 0;
}

.user-avatar {
  border: 4px solid #fff;
  font-size: 32px;
  font-weight: bold;
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-name {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.user-account {
  margin: 0 0 12px 0;
  color: #909399;
  font-size: 14px;
}

.user-profile {
  margin: 12px 0 0 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex-shrink: 0;
}

/* 统计信息网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: none;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 24px;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
}

.stat-icon.total {
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
}

.stat-icon.easy {
  background: linear-gradient(135deg, #67c23a 0%, #52c41a 100%);
}

.stat-icon.medium {
  background: linear-gradient(135deg, #e6a23c 0%, #faad14 100%);
}

.stat-icon.hard {
  background: linear-gradient(135deg, #f56c6c 0%, #ff4d4f 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  margin: 4px 0 0 0;
  color: #909399;
  font-size: 14px;
}

/* 最近活动卡片 */
.activity-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.activity-list {
  max-height: 300px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  gap: 16px;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.activity-icon.activity-solve {
  background: #e8f5e8;
  color: #67c23a;
}

.activity-icon.activity-favorite {
  background: #fff3e0;
  color: #e6a23c;
}

.activity-icon.activity-achievement {
  background: #e3f2fd;
  color: #409eff;
}

.activity-icon.activity-default {
  background: #f5f7fa;
  color: #909399;
}

.activity-content {
  flex: 1;
  min-width: 0;
}

.activity-title {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
  line-height: 1.4;
}

.activity-time {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

/* 快速操作卡片 */
.quick-actions-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 8px;
}

.action-btn {
  height: 60px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background: #ecf5ff;
  transform: translateY(-1px);
}

.action-btn span {
  font-size: 13px;
}

/* 账户信息卡片 */
.account-info-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 8px;
}

.info-item {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
}

.info-item:hover {
  background: #e9ecef;
  border-color: #dee2e6;
}

.label {
  font-weight: 500;
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.value {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

/* 调试相关 */
.debug-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.debug-card pre {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  font-size: 12px;
  color: #495057;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 400px;
  overflow-y: auto;
  margin: 0;
}

.debug-toggle {
  text-align: center;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .profile-container {
    max-width: 800px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .user-header {
    flex-direction: column;
    text-align: center;
    padding: 24px;
  }
  
  .action-buttons {
    flex-direction: row;
    justify-content: center;
    width: 100%;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .activity-item {
    padding: 12px 16px;
  }
}

@media (max-width: 480px) {
  .user-name {
    font-size: 20px;
  }
  
  .stat-content {
    padding: 20px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
}
</style>
